package com.example.spring_mybatis.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.example.spring_mybatis.utils.RUtil;
import com.example.spring_mybatis.core.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.spring_mybatis.model.RoleEntity;
import com.example.spring_mybatis.mapper.RoleMapper;
import com.example.spring_mybatis.service.IRoleService;
import com.example.spring_mybatis.dto.RoleDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.HashMap;
import java.util.Map;
/**
 * <p>
 * 角色表(也可以当部门表) 服务实现类
 * </p>
 *
 * @作者: 水痕
 * @时间: 2023-09-17 21:55:23
 * @描素:
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public RUtil<String> createApi(RoleDTO RoleDTO) {
        RoleEntity Role = new RoleEntity();
        BeanUtils.copyProperties(RoleDTO, Role);
        int insert = this.roleMapper.insert(Role);
        if (insert==1) {
            return RUtil.success("创建成功");
        } else {
            return RUtil.error("创建失败");
        }
    };

    @Override
    public RUtil<String> deleteByIdApi(Integer id) {
        int affectRow = this.roleMapper.deleteById(id);
        if (affectRow == 1) {
            return RUtil.success("删除成功");
        } else {
            return RUtil.error("删除失败");
        }
    }

    @Override
    public RUtil<String> modifyByIdApi(Integer id, RoleDTO RoleDTO) {
        RoleEntity Role = new RoleEntity();
        BeanUtils.copyProperties(RoleDTO, Role);
        int affectRow = this.roleMapper.updateById(Role);
        if (affectRow == 1) {
            return RUtil.success("更新成功");
        } else {
            return RUtil.error("更新失败");
        }
    }

    @Override
    public Map<String, Object> getDataPageApi(Integer pageNumber, Integer pageSize) {
        IPage page = new Page(pageNumber,pageSize);
        IPage iPage = this.roleMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        map.put("list", iPage.getRecords());
        map.put("total", iPage.getTotal());
        return map;
    }

    @Override
    public RoleEntity getByIdApi(Integer id) {
        LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleEntity::getId, id);
        RoleEntity Role = this.roleMapper.selectOne(queryWrapper);
        if (Role == null) {
            throw new CommonException("你传递的id不存在");
        }
        return Role;
    }
}